package com.miao.service.jobhandler;

import com.miao.base.utils.Mp4VideoUtil;
import com.miao.mapper.MediaFilesMapper;
import com.miao.mapper.MediaProcessMapper;
import com.miao.pojo.MediaProcess;
import com.miao.service.IMediaFilesService;
import com.miao.service.IMediaProcessService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

//视频任务处理类
@Slf4j
@Component
public class VideoTask {

    private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

    @Autowired
    private MediaProcessMapper mediaProcessMapper;
    @Autowired
    private IMediaProcessService mediaProcessService;
    @Autowired
    private IMediaFilesService mediaFilesService;
    @Value("${videoprocess.ffmpegpath}")
    private String ffmpegPath;


    /**
     * 2、分片广播任务
     */
    @Transactional
    @XxlJob("videoJobHandler")
    public void videoJobHandler() throws Exception {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();//执行器序号
        int shardTotal = XxlJobHelper.getShardTotal();//执行器总数

        //查询任务
        List<MediaProcess> listOfProcessOfXll = mediaProcessMapper.getListOfProcessOfXll(shardTotal, shardIndex, 2);
        int size = listOfProcessOfXll.size();
        int now = 2;
        if(size < 2){
            now = size;
        }

        for (MediaProcess m : listOfProcessOfXll) {
                     //开启任务
                     Long id = m.getId();
                     int i = mediaProcessMapper.startTask(id);
                     if (i <= 0) {
                         log.info("抢占任务失败");
                         return;
                     }
                     //获取文件到本地
                     File file = mediaFilesService.downLoadFiles(m.getBucket(), m.getFilePath());
                     if (file == null) {
                         log.info("下载文件出错");
                         mediaProcessService.saveProcessFinish(id, "3", m.getFileId(), "下载文件出错", null);
                         return;
                     }
                     //获取下载的文件的路径
                     String absolutePath = file.getAbsolutePath();
                     //获取转换后的名称(其实是无效参数)
                     String name = m.getFileId() + ".mp4";//m.getFileId()为md5
                     File minio = null;//创建临时文件作为转换后的文件
                     try {
                         minio = File.createTempFile("minio", ".mp4");
                     } catch (IOException e) {
                         e.printStackTrace();
                         log.error("创建转换后文件失败");
                         mediaProcessService.saveProcessFinish(id, "3", m.getFileId(), "创建转换后文件失败", null);
                         return;
                     }
                     String absolutePath2 = minio.getAbsolutePath();
                     //name其实是无用参数
                     Mp4VideoUtil mp4VideoUtil = new Mp4VideoUtil(ffmpegPath, absolutePath, name, absolutePath2);
                     String result = mp4VideoUtil.generateMp4();
                     //失败
                     if (!result.equals("success")) {
                         log.error("视频转码失败！");
                         mediaProcessService.saveProcessFinish(id, "3", m.getFileId(), "视频转码失败", null);
                         return;
                     }
                     //成功
                     //上传minio
                     String md5OfFile = mediaFilesService.getMd5OfFile(minio);
                     String bigFilePath = mediaFilesService.getBigFilePath(md5OfFile, ".mp4");
                     boolean toMinio = mediaFilesService.addToMinio(minio.getAbsolutePath(), "video/mp4", m.getBucket(), bigFilePath);
                     if (!toMinio) {
                         log.error("上传到minio失败");
                         mediaProcessService.saveProcessFinish(id, "3", m.getFileId(), "上传minio失败", null);
                         return;
                     }
                     String url = "/video/" + mediaFilesService.getBigFilePath(md5OfFile, ".mp4");
                     mediaProcessService.saveProcessFinish(id, "2", m.getFileId(), "无", url);


//             });
        }

        //阻塞,指定最大限制的等待时间，阻塞最多等待一定的时间后就解除阻塞
//        countDownLatch.await(30, TimeUnit.MINUTES);


    }




}
